<template>
  <div class="alanalysis">
    <div class="alanalysis-bridge">
      <CardContainer headerName="加速度分析">
        <!--        Yu 选择桥梁这一块逻辑有点不是通！！ 注销掉-->
        <!--        <template slot="header-right">-->
<!--          <div class="search">-->
<!--            <el-button class="seletBtn top" size="small" type="success" icon="el-icon-circle-plus-outline"-->
<!--                       @click="selectBridge">选择桥梁</el-button>-->
<!--            <el-tabs class="top" v-model="editableTabsValue" type="card" closable @tab-remove="removeTab">-->
<!--              <el-tab-pane size="small" :key="item.id" v-for="(item, index) in editableTabs" :label="item.name"-->
<!--                           :name="item.id"></el-tab-pane>-->
<!--            </el-tabs>-->
<!--          </div>-->
<!--        </template>-->
        <template slot="card-content">
          <div class="alanalysis-bridge-card">
            <div>
              <point :bridgeId="bridgeId" :type="type" @child-event="getPoint"></point>
            </div>
          </div>
        </template>
      </CardContainer>
    </div>

    <div class="alanalysis-chart">
      <div class="alanalysis-chart-time">
        <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00']"
                        style="width:100%" v-model="chartTime" type="datetimerange" size="small" range-separator="-"
                        start-placeholder="开始时间" end-placeholder="结束时间"  @change="handleChange">
        </el-date-picker>
      </div>
      <div class="alanalysis-chart-box">
        <p class="alanalysis-chart-info">
          加速度最大值：{{max.toFixed(2)}}mm/s²、最小值：{{min.toFixed(2)}}mm/s²
          <el-checkbox v-model="checked" style="margin-left:20px;">阈值</el-checkbox>
        </p>
        <div class="alanalysis-chart-all" id="stressLine"></div>
      </div>
    </div>

    <SelectBridge ref="selectBridge" @getData="getData"></SelectBridge>
  </div>
</template>

<script>
  import CardContainer from "@/views/healthMonitor/components/CardContainer";
  import echarts from "echarts";
  import point from "./components/point";
  import SelectBridge from "@/views/healthMonitor/components/SelectBridge";
  import moment from "moment";
  import {
    mapState,
    mapMutations
  } from "vuex";
  export default {
    data() {
      return {
        type: 'ZD',
        line: null,
        chartTime: '',
        bridgeId: "",
        editableTabs: [],
        editableTabsValue: "",
        max: 0,
        min: 0,
        sensorCode: '',
        markLine:[],
        id:'',
        checked:false,
      };
    },
    components: {
      CardContainer,
      SelectBridge,
      point
    },
    computed: {
      ...mapState("acceleration", {
        bridgeId: "bridgeId"
      }),
    },
    watch: {
      bridgeId: {
        handler(newName, oldName) {
          //变化数据
          this.sensorCode = '';
          this.min = 0;
          this.max = 0;

          if (this.line) {
            this.line.clear();
            this.line.dispose();
          }
          this.$nextTick(() => {
            this.drawLine([]);
          });
        },
        immediate: true,
      },
      checked: {
        handler(newVal) {
          if(newVal) {
           // console.log("aaa")
            this.markLine = [];
            this.getLine();
            this.getAccelerationNum(this.sensorCode);
            this.getAccelerationLineData(this.sensorCode);
          }
          else {
            this.markLine = [];
            this.getAccelerationNum(this.sensorCode);
            this.getAccelerationLineData(this.sensorCode);
          }
        },
      },
      editableTabsValue: {
        handler(newVal) {
          this.setBridgeId(newVal);
          this.bridgeId = newVal;
        },
      },
    },
    created() {
      this.getBridgeAll();
      const endTime = moment(new Date()).format("YYYY-MM-DD") + ' 00:00:00';
      const startTime = this.getDay(-2) + ' 00:00:00';
      this.chartTime = [startTime, endTime];
    },
    mounted() {
      this.drawLine([]);
      window.addEventListener("resize", () => {
        if (this.line) {
          this.line.resize();
        }
      });
    },
    methods: {
      getLine(){
        console.log("start!")
      // 获取上下限值
          this.$api.mearsuringPointSetting
            .getWarningLine({
              measurePointId: this.id
            })
            .then(res => {
              console.log("SXX:",res)
              console.log("上下线值", res.data.data[0][0]);
              this.markLine = [];
              let data = res.data.data[0][0];
              if (data.firstCap) {
                this.markLine.push({
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: "dashed",
                    color: "rgba(89, 84, 84, 1)",
                    width: 1
                  },
                  label: {
                    position: "end",
                    formatter: "一级上限" + `(${data.firstCap})`
                  },
                  yAxis: data.firstCap // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                });
              }
              if (data.firstFloor) {
                this.markLine.push({
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: "dashed",
                    color: "rgba(89, 84, 84, 1)",
                    width: 1
                  },
                  label: {
                    position: "end",
                    formatter: "一级下限" + `(${data.firstFloor})`
                  },
                  yAxis: data.firstFloor // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                });
              }

              if (data.secondCap) {
                this.markLine.push({
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: "dashed",
                    color: "rgba(245, 166, 35, 1)",
                    width: 1
                  },
                  label: {
                    position: "end",
                    formatter: "二级上限" + `(${data.secondCap})`
                  },
                  yAxis: data.secondCap // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                });
              }
              if (data.secondFloor) {
                this.markLine.push({
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: "dashed",
                    color: "rgba(245, 166, 35, 1)",
                    width: 1
                  },
                  label: {
                    position: "end",
                    formatter: "二级下限" + `(${data.secondFloor})`
                  },
                  yAxis: data.secondFloor // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                });
              }

              if (data.thirdCap) {
                this.markLine.push({
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: "dashed",
                    color: "rgba(220, 81, 81, 1)",
                    width: 1
                  },
                  label: {
                    position: "end",
                    formatter: "三级上限" + `(${data.thirdCap})`
                  },
                  yAxis: data.thirdCap // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                });
              }

              if (data.thirdFloor) {
                this.markLine.push({
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: "dashed",
                    color: "rgba(220, 81, 81, 1)",
                    width: 1
                  },
                  label: {
                    position: "end",
                    formatter: "三级下限" + `(${data.thirdFloor})`
                  },
                  yAxis: data.thirdFloor // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                });
              }
               // this.drawLine(this.data)
                console.log("0000000000000000000000000000000000000000000000000000000000000000000000000",this.markLine);
            });
    },
      getPoint(data,id) {
        if (data) {
          this.sensorCode = data;
          this.id = id;
          this.getAccelerationNum(data);
          this.markLine = [];
          if(this.checked) {
          this.getLine();
          this.getAccelerationLineData(data);
          }
          else {
            this.getAccelerationLineData(data);
          }
        }
      },
      getAccelerationNum(sensorCode) {
        const _params = {
          bridgeId: this.bridgeId,
          // bridgeId:'758335110117326848',
          sensorCode: sensorCode,
          // sensorCode:'JSD-05-02',
          beginTime: this.chartTime[0],
          endTime: this.chartTime[1]
        }
        this.$api.analysis.queryAccelerationNum(_params).then(response => {
          console.log('最大值最小值是');
          console.log(response);
          if (response.data.success) {
            const _data = response.data.data || {};
            this.max = _data['max'] || 0;
            this.min = _data['min'] || 0;
          }
        });
      },
      getAccelerationLineData(sensorCode) {
        const _params = {
          bridgeId: this.bridgeId,
          // bridgeId:'758335110117326848',
          sensorCode: sensorCode,
          // sensorCode:'JSD-05-02',
          beginTime: this.chartTime[0],
          endTime: this.chartTime[1]
        }
        this.$api.analysis.queryAccelerationLine(_params).then(response => {
          console.log('折现图');
          console.log(response);
          if (response.data.success) {
            const _data = response.data.data || [];
            let lineData = this.handleArrayfromOneToTwo(_data, 'dateAndTime', 'squarValue');
            console.log(lineData);
            this.drawLine(lineData);
          }
        });
      },
      handleChange(val) {
        if (!this.chartTime) {
          this.$vs.notify({
            text: '请选择时间',
            color: "danger"
          });
          return false;
        }
        if(this.checked) {
          this.getLine();
        }
        else {
          this.markLine = [];
        }
        if (this.line) {
          this.line.clear();
          this.line.dispose();
        }
        if (this.sensorCode) {
          this.getAccelerationNum(this.sensorCode);
          this.getAccelerationLineData(this.sensorCode);
        } else {
          this.$nextTick(() => {
            this.drawLine([]);
          })
        }
      },
      drawLine(_seriesData) {
        this.line = new echarts.init(
          document.getElementById('stressLine')
        );
        this.line.setOption({
          title: {
            top: '45px',
            left: 'center',
            text: '加速度趋势分析',
            textStyle: {
              align: 'center',
              color: '#699EE5',
              fontSize: 18,
            }
          },
          grid: {
            top: '35%',
            right: '6%',
            left: '5%',
            bottom: '12%'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985',
                fontSize: 12
              },
            },
            textStyle: {
              fontSize: '100%'
            }
          },
          xAxis: [{
            type: 'time',
            min: this.chartTime[0],
            max: this.chartTime[1],
            splitNumber: 14,

            axisLine: {
              show: true,
              lineStyle: {
                color: "#E5E6EB"
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: "#E5E6EB"
              }
            },
            boundaryGap: false,
            axisLabel: {
              color: "#A7A6AF",
              fontSize: 12
            }
          }],
          yAxis: [{
            type: 'value',
            max: (value)=> {
            if(this.markLine[4]){
              return this.markLine[4].yAxis
            }else{
              return (value.max).toFixed(2);
            }
          },
          min: (value)=> {
            if(this.markLine[5]){
              return this.markLine[5].yAxis
            }else{
              return (value.min).toFixed(2);
            }
          },
            name: '加速度（mm/s²）',
            nameTextStyle: {
              padding: 30,
              color: "#A7A6AF",
              fontSize: 12
            },
            position: 'left',
            nameLocation: 'middle',
            axisTick: {
              show: false
            },
            splitNumber: 4,
            splitLine: {
              show: false
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: ['#F5F6FA', '#fff']
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "#E5E6EB"
              },
            },
            axisLabel: {
              color: "#A7A6AF",
              fontSize: 12
            }
          }],
          series: [{
            data: _seriesData,
            type: 'line',
            symbol: 'none',
            lineStyle: {
              color: '#699EE5'
            },
            itemStyle: {
              color: '#699EE5',
              borderWidth: 1
            },
            markLine:{
              symbol: "none",
              label: {
                position: "middle" //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
              },
              data: this.markLine
            }
          }]
        });
      },
      getDay(number) {
        let currentDate = new Date(),
          currentTime = currentDate.getFullYear() + "-" + ((currentDate.getMonth() + 1) < 10 ?
            `0${(currentDate.getMonth() + 1)}` : (currentDate.getMonth() + 1)) + "-" + (currentDate.getDate() < 10 ?
            `0${currentDate.getDate()}` : currentDate.getDate());
        let frontDate = new Date(currentDate);
        frontDate.setDate(currentDate.getDate() + number);
        let frontTime = frontDate.getFullYear() + "-" + ((frontDate.getMonth() + 1) < 10 ?
          `0${(frontDate.getMonth() + 1)}` : (frontDate.getMonth() + 1)) + "-" + (frontDate.getDate() < 10 ?
          `0${frontDate.getDate()}` : frontDate.getDate());
        return frontTime;
      },
      handleArrayfromOneToTwo(_array, m, n) {
        return _array.map(item => [item[m], item[n]]);
      },
      //桥梁选择
      selectBridge() {
        this.$refs.selectBridge.init();
      },
      getData(val) {
        this.bridgeId = val[0].id;
        this.editableTabs = val;
        this.editableTabsValue = val[0].id;
        this.setBridgeId(val[0].id);
      },
      ...mapMutations("acceleration", {
        setBridgeId: "BRIDGEID"
      }),
      handleTabClick(tab, event) {
        this.activeTabName = tab.name;
      },
      removeTab(id) {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === id) {
          tabs.forEach((tab, index) => {
            if (tab.id === id) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.id;
              }
            }
          })
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter((tab) => tab.id !== id);
        this.setBridgeId(this.editableTabsValue);
      },
      getBridgeAll() {
        this.$api.mearsuringPointSetting.getBridgeAll().then((res) => {
          let bridgeListAll = res.data.data[0];
          console.log("res的值",bridgeListAll);
          //let qlId=[];
          let data = JSON.parse(localStorage.getItem("ownInfo"));
          console.log("data的值1111",data[0].code);
          bridgeListAll.map((item, key) =>{
            if(item.id==data[0].code){
              //this.editableTabs = [bridgeListAll[0]];
              this.editableTabs = [item];
              this.editableTabsValue = item.id;
              this.setBridgeId(item.id);
            }
          })
        })
      },
    },
  }

</script>
<style lang='scss' scoped>
  /deep/.el-tabs__item {
    height: 32px;
    line-height: 32px;
    font-size: 12px;
  }

  /deep/.el-tabs__nav-wrap {
    height: 32px;
  }

  /deep/.el-tabs--card>.el-tabs__header .el-tabs__item .el-icon-close {
    top: -2px;
  }

  /deep/.el-tabs--card>.el-tabs__header .el-tabs__item {
    border-bottom: 1px solid #e4e7ed !important;
  }

  /deep/.is-active.el-tabs__item.is-top.is-active.is-closable {
    background: #327bdc !important;
    color: #fff !important;
  }

  .alanalysis {
    &-bridge {
      &-card {
        width: 100%;
        height: 300px;
      }

      &-search {
        margin: 20px 0;
      }
    }

    &-chart {
      margin: 20px 0;
      width: 100%;
      height: 430px;
      background: #fff;
      position: relative;


      &-time {
        width: 340px;
        position: absolute;
        right: calc(2% + 10px);
        top: 15px;
        z-index: 999;
      }


      &-box {
        width: 100%;
        height: 100%;
        padding: 20px 10px 10px;
        clear: both;
      }

      &-all {
        width: 100%;
        height: 100%;
      }

      &-info {
        position: absolute;
        top: 20px;
        left: 40px;
        font-size: 12px;
        font-weight: 400;
        color: rgba(153, 153, 153, 1);
      }

      &-left {
        width: 25%;
        height: 100%;
        float: left;
      }

      &-right {
        width: 75%;
        height: 100%;
        float: right;
      }

      &-average {
        width: 50%;
        height: 100%;
        float: left;
      }
    }
  }

  .search {
    display: flex;
    justify-content: start;
    background: #fff;
    border-radius: 3px;
    height: 32px;

    .seletBtn {
      margin-right: 20px;
      height: 32px;
    }

    .top {
      position: relative;
      top: 6px;
    }
  }

</style>







